﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;

namespace iSet
{
    public partial class Login : Form
    {

        QT.Windows.SafeTokenHandle pToken;

        public Login()
        {
            InitializeComponent();
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.ExitThread();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (QT.Windows.WinLogon.Logon(this.tbUser.Text, this.tbPass.Text, out pToken))
            {
                if (DB.UpdateUser(this.tbUser.Text.Trim(), QT.Security.AESHelper.AESEncrypt(this.tbPass.Text.Trim())) <= 0)
                {
                    MessageBox.Show("保存失败");
                    return;
                }

                using (pToken)
                {
                    //模拟用户   
                    using (WindowsIdentity.Impersonate(pToken.DangerousGetHandle()))
                    {
                        if (!QT.Windows.WinLogon.IsAdministrators())
                        {
                            MessageBox.Show(this.tbUser + "不是管理员");
                            return;                           
                        }
                    }
                }

                if (System.Environment.OSVersion.Version.Major >= 6)
                {
                    QT.Windows.WinLogon.CreateProcess(this.tbUser.Text.Trim(), this.tbPass.Text.Trim(), Application.StartupPath, Application.ExecutablePath, Process.GetCurrentProcess().ProcessName);
                    Application.Exit();
                }

                this.WindowState = FormWindowState.Maximized;
                this.Hide();
            }
            else
            {
                MessageBox.Show("用户名密码错误");
                return;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }
    }
}
